import json
import re
import time
import pymysql
import requests
import smtplib
import execjs
from email.mime.text import MIMEText

tablename = 'yanyun'
username = 'zhanwei'


class AccountChecker:
    def __init__(self):
        self.db = self.connect_database()
        self.cursor = self.db.cursor()
        self.account_info = {
            'price': 0,
            'danjia': 0,
            'qufu': 'None',
            'des': 'None'
        }

    def judgecondition(self, user):
        if user[4] is not None and self.account_info['danjia'] > user[4]:
            return 0
        # if user[2] is not None and self.account_info['qufu'] not in user[2]:
        #    return 0
        if user[3] is not None and self.account_info['price'] > user[3]:
            return 0
        return 1

    @staticmethod
    def js_from_file(file_name):
        """
        读取js文件
        :return:
        """
        with open(file_name, 'r', encoding='UTF-8') as file:
            result = file.read()
        return result

    @staticmethod
    def checkExist(str):
        toFind = ['琼华白羽', '银河星沙', '曦光璞玉', '银河星纱']
        for tmp in toFind:
            if tmp in str:
                return 1
        return 0

    @staticmethod
    def connect_database():
        try:
            return pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='panzhi')
        except Exception as e:
            print(f'Database connection failed: {e}')
            exit()

    @staticmethod
    def send_email(content, email, myprice):
        mail_host = 'smtp.163.com'
        mail_user = 'vjmbsd'
        mail_pass = 'HVYZEVNOSEOYSADS'
        sender = 'vjmbsd@163.com'
        receivers = [email] if email else ['2391860056@qq.com']

        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = f'{myprice}'
        message['From'] = sender
        message['To'] = ';'.join(receivers)

        try:
            smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
            # 登录到服务
            smtp.login(mail_user, mail_pass)
            # 发送
            smtp.sendmail(sender, receivers, message.as_string())
            # 退出
            smtp.quit()
            print('Email sent successfully')
        except smtplib.SMTPException as e:
            print(f'Error sending email: {e}')
            mail_user = 'nshyx2292601665'
            mail_pass = 'HNtAz6quUg4ncav3'
            sender = 'nshyx2292601665@163.com'
            smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
            # 登录到服务
            smtp.login(mail_user, mail_pass)
            # 发送
            smtp.sendmail(sender, receivers, message.as_string())
            # 退出
            smtp.quit()
            print('Email1 sent successfully')

    def check_and_notify_users(self):
        try:
            with self.db.cursor() as cursor:
                sql = f"SELECT * FROM {username} WHERE expiration_date >= CURDATE()"
                cursor.execute(sql)
                users = cursor.fetchall()
                for user in users:
                    if self.judgecondition(user) == 1:
                        self.send_email(
                            self.account_info['des'],
                            user[1],
                            f"总价: {self.account_info['price']} 均价：{self.account_info['danjia']} {self.account_info['qufu']}"
                        )
        except Exception as e:
            print(f"Error checking and notifying users: {e}")

    def getpanzhidata(self):
        url = "https://api.pzds.com/api/web-client/v2/public/goodsPublic/page"
        payload = '''{\"order\":\"DESC\",\"sort\":\"onStandTime\",\"page\":1,\"pageSize\":21,\"action\":{\"gameId\":\"359\",\"goodsCatalogueId\":6,\"merchantMark\":null,\"keywords\":[],\"searchWords\":[],\"searchPropertyIds\":[],\"unionGameIds\":[],\"goodsSearchActions\":[]}}'''
        context1 = execjs.compile(self.js_from_file('./test.js'))
        result1 = context1.call("myJiaMi", str(payload))
        headers = {
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "channelinfo": "{\"channelCode\":null,\"tag\":null,\"channelType\":null,\"searchWord\":\"null\"}",
            "content-type": "application/json",
            "pzos": "windows",
            "pzplatform": "pc",
            "pztimestamp": str(result1['Timestamp']),
            "pzversion": "1.0.0",
            "pzversioncode": "1",
            "random": str(result1['Random']),
            "sign": str(result1['strMd5']),
            "skey": "CLIENT",

        }
        try:
            response = requests.request('post', url, headers=headers, data=payload)
            mydict = json.loads(response.text)
            a = mydict['data']['records']
            for tmp in a:
                try:
                    bianhao = tmp['goodsNo']
                    mysearch = f"select * from {tablename} where bianhao='{bianhao}'"
                    self.cursor.execute(mysearch)
                    if not len(self.cursor.fetchall()):
                        self.account_info['price'] = tmp['price']
                        self.account_info['des'] = tmp['title']
                        toSearch=self.account_info['des']
                        if '龙骨图' in toSearch or '5亿' in toSearch or '五亿' in toSearch :
                            self.send_email(self.account_info['des'],'1779601135@qq.com',self.account_info['price'])

                        sql = f"insert into {tablename}(bianhao,des) values('{bianhao}','{self.account_info['des'][:500]}') "
                        self.cursor.execute(sql)
                        self.db.commit()
                except Exception as eee:
                    self.db.rollback()
                    print('getpanzhidata:' + eee.__str__())
        except  Exception as e:
            self.db.rollback()
            print('getpanzhidata:' + e.__str__())

    def clean_expired_users(self):
        try:
            with self.db.cursor() as cursor:
                sql = f"DELETE FROM {username} WHERE expiration_date < CURDATE()"
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print(f"Error cleaning expired users: {e}")
            self.db.rollback()


if __name__ == '__main__':
    account_checker = AccountChecker()
    while True:
        print(1)
        ##account_checker.clean_expired_users()
        account_checker.getpanzhidata()
        time.sleep(30)
